package cn.xyafu.lost.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.xyafu.lost.R;
import cn.xyafu.lost.adapter.NewsBodyAdapter;
import cn.xyafu.lost.pojo.News;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class UserNewsActivity extends AppCompatActivity {

    private String uid;

    private Button news_back_btn;
    private ListView lv_news;

    private EditText edt_send_msg;
    private Button btn_send_msg;

    private List<News> news;    // 当前用户的 news

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    OkHttpClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_user_news);
        uid = "7";  // 默认值
        // 当前用户 uid
        Intent intent = getIntent();
        uid = intent.getStringExtra("uid");
        // 初始化页面
        initView();

        // 初始化OkHttp
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        client = builder.build();

        // 初始化listview
        initData();

        // 点击返回
        news_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private void sendStateToast(final Boolean flag){
        btn_send_msg.post(new Runnable() {
            @Override
            public void run() {
                if (flag){
                    Toast.makeText(UserNewsActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(UserNewsActivity.this, "网络异常，请稍后再试", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void showSendDialog(final String rid){

        LayoutInflater inflater = LayoutInflater.from(UserNewsActivity.this);
        View textEntryView = inflater.inflate(R.layout.dialog_sendmsg, null);
        edt_send_msg = textEntryView.findViewById(R.id.edt_send_msg);
        btn_send_msg = textEntryView.findViewById(R.id.btn_send_msg);
        AlertDialog.Builder builder = new AlertDialog.Builder(UserNewsActivity.this);
        builder.setTitle("发送消息");
        builder.setView(textEntryView);
        final Dialog dialog =  builder.show();
        WindowManager.LayoutParams wlp =dialog.getWindow().getAttributes();wlp.gravity = Gravity.TOP | Gravity.LEFT;
        wlp.x=10;
        wlp.y=240;
        dialog.getWindow().setLayout(720,580);

        btn_send_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = edt_send_msg.getText().toString().trim();
                //  发起网络请求
                // (1). 创建OkHttpCLient对象
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.connectTimeout(5, TimeUnit.SECONDS);
                builder.readTimeout(5, TimeUnit.SECONDS);
                builder.writeTimeout(5, TimeUnit.SECONDS);
                OkHttpClient client = builder.build();
                // (2). 创建Request对象
                Request request = new Request.Builder().url(
                        "http://localhost/Lost_ssm/android/sendNews?rid="+ rid +"&sid="+ uid +"&nmsg="+ content).get().build();
                // (3). 创建Call对象
                Call call = client.newCall(request);
                // (4). 将请求添加到队列中
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println("请求失败");
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        System.out.println("请求成功");
                        // 将json数据转化为model数据
                        Boolean flag = Boolean.parseBoolean(response.body().string());
                        if (flag){
                            sendStateToast(true);
                            dialog.dismiss();
                        }else{
                            sendStateToast(false);
                        }
                    }
                });

            }
        });

    }

    // 设置listview 的 item点击事件
    private void setItemClickListener(ListView listView){
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = view.findViewById(R.id.news_send_uid);
                String rid = textView.getText().toString().trim();

                showSendDialog(rid);

            }
        });
    }

    //设置长按事件
    private void setItemLongClickListener(ListView listView){

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                TextView textView = view.findViewById(R.id.news_send_nid);
                final String nid = textView.getText().toString().trim();

                //定义AlertDialog.Builder对象，当长按列表项的时候弹出确认删除对话框
                AlertDialog.Builder builder=new AlertDialog.Builder(UserNewsActivity.this);
                builder.setMessage("确定删除?");
                builder.setTitle("提示");

                //添加AlertDialog.Builder对象的setPositiveButton()方法
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(news.remove(position)!=null){
                            // (2). 创建Request对象
                            Request request = new Request.Builder().url("http://localhost/Lost_ssm/android/deleteNews?nid="+nid).get().build();
                            // (3). 创建Call对象
                            Call call = client.newCall(request);
                            // (4). 将请求添加到队列中
                            call.enqueue(new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    System.out.println("请求失败");
                                    e.printStackTrace();
                                }

                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    System.out.println("请求成功");
                                    updateView();
                                }
                            });
                        }else {
                            System.out.println("failed");
                        }
                        Toast.makeText(getBaseContext(), "删除", Toast.LENGTH_SHORT).show();
                    }
                });

                //添加AlertDialog.Builder对象的setNegativeButton()方法
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                builder.create().show();

                // return true 代表当前当前长按，longClick独占，不会触发onclick
                return true;

            }
        });

    }

    // 更新listview
    private void updateView(){
        news_back_btn.post(new Runnable() {
            @Override
            public void run() {
                NewsBodyAdapter adapter = new NewsBodyAdapter(UserNewsActivity.this,news);
                lv_news.setAdapter(adapter);
                setItemClickListener(lv_news);
                setItemLongClickListener(lv_news);
            }
        });

    }

    private void initData(){
        // (2). 创建Request对象
        Request request = new Request.Builder().url("http://localhost/Lost_ssm/android/showNews?uid="+uid).get().build();
        // (3). 创建Call对象
        Call call = client.newCall(request);
        // (4). 将请求添加到队列中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("请求成功");
                // 1. 将json数据转化为model数据
                String jsonString = response.body().string();
                //添加到list中
                news = JSON.parseArray(jsonString, News.class);
                updateView();
            }
        });


    }

    private void initView(){
        news_back_btn = findViewById(R.id.news_back_btn);
        lv_news = findViewById(R.id.lv_news);
    }

}
